from typing import Optional
from sqlalchemy.orm import Session
from app.crud.base import CRUDBase
from app.models.user_config import UserConfig
from app.schemas.user_config import UserConfigCreate, UserConfigUpdate

class CRUDUserConfig(CRUDBase[UserConfig, UserConfigCreate, UserConfigUpdate]):
    def get_by_api_key(self, db: Session, api_key: str) -> Optional[UserConfig]:
        """通过API密钥获取配置"""
        return db.query(UserConfig).filter(UserConfig.api_key == api_key).first()
    
    def get_default_config(self, db: Session) -> UserConfig:
        """获取或创建默认配置"""
        config = db.query(UserConfig).first()
        if not config:
            config = UserConfig()
            db.add(config)
            db.commit()
            db.refresh(config)
        return config
    
    def update_theme(self, db: Session, *, theme: str) -> UserConfig:
        """更新主题设置"""
        config = self.get_default_config(db)
        config.theme = theme
        db.add(config)
        db.commit()
        db.refresh(config)
        return config

user_config = CRUDUserConfig(UserConfig) 